package cn.basic.utils;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 自己码对象工具类
 */
public class ClassUtils {

    /**
     * 获取一个包下面的所有类全限定名
     * @param packageNames 包
     * @return List<Class>
     */
    public static List<Class> getAllClassName(String packageNames){
        String[] split = packageNames.split(",");
        List<Class> result = new ArrayList<>();
        for (String packageName : split) {
            // 包相对路径
            String packagePath = packageName.replace(".","/"); //把包路径中的点替换为目录
            // 资源URL
            URL url = ClassLoader.getSystemResource(""); //获取classapth
            try {
                Resource[] resources = new PathMatchingResourcePatternResolver().
                        getResources(ResourceUtils.CLASSPATH_URL_PREFIX + packagePath + "/*.*");
                // 循环images文件夹下的所有文件
                for (Resource fileResource : resources) {
                    //输出文件名称
                    String fileName = fileResource.getFilename();
                    fileName = fileName.substring(0, fileName.lastIndexOf("."));
                    String allName = packageName + "." + fileName;
                    System.out.println(allName);
                    result.add(Class.forName(allName));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}